#!/bin/sh

. /etc/rc.freenas

cifs_file="/tmp/.cifs_LDAP"
status_file="/var/run/directoryservice.ldap"
service=/usr/sbin/service
python=/usr/local/bin/python
notifier=/usr/local/bin/midclt

ldapctl_cmd()
{
	local args="$*"

	if [ -n "${args}" ]
	then
		logger -t LDAP "${args}"
		${args}
		return $?
	fi

	return 0
}

sssd_running()
{
	${service} sssd onestatus >/dev/null 2>&1
	return $?
}

sssd_start()
{
	ldapctl_cmd ${service} sssd onestart
	return $?
}

sssd_stop()
{
	ldapctl_cmd ${service} sssd onestop
	return $?
}

sssd_restart()
{
	ldapctl_cmd ${service} sssd onestop
	ldapctl_cmd ${service} sssd onestart
	return $?
}

cifs_enabled()
{
	srv_enabled cifs && return 0
	return 1
}

cifs_restart()
{
	ldapctl_cmd ${python} ${notifier} call notifier.stop cifs
	ldapctl_cmd ${python} ${notifier} call notifier.start cifs
	return $?
}

cifs_reset()
{
	ldapctl_cmd ${service} ix-pre-samba start

	if cifs_enabled;
	then
		cifs_restart
	fi
}

ldapctl_start()
{
	local ldap_started=0
	local realm
	local keytab_principal

	if ! LDAP_init
	then
		ldap_set 0
		return 1
	fi

	if ldap_enabled
	then
		ldap_started=1
	else		
		ldap_set 1
	fi

	if ! ldapctl_cmd ${service} ix-ldap quietstart
	then
		ldap_set 0
		cifs_reset
		return 1
	fi

	ldap_krb_realm="$(LDAP_get ldap_krb_realm)"
	if [ -n "${ldap_krb_realm}" ]
	then
		ldapctl_cmd ${service} ix-kerberos quietstart default "${ldap_krb_realm}"
	fi

	ldapctl_cmd ${service} ix-nsswitch quietstart

	realm="$(LDAP_get ldap_krb_realm)"
	keytab_principal="$(LDAP_get ldap_keytab_principal)"

	if [ -n "${realm}" -o -n "${keytab_principal}" ]
	then
		ldapctl_cmd ${service} ix-kinit quietstart
		if ! ldapctl_cmd ${service} ix-kinit status
		then
			ldap_set 0
			cifs_reset
			return 1
		fi  
	fi

	anonbind="$(LDAP_get ldap_anonbind)"
	if [ "${anonbind}" = "0" ]
	then
		ldapctl_cmd ${service} ix-sssd start	
		if sssd_running
		then
			sssd_restart
		else
			sssd_start
		fi
	
	fi

	if ! ldapctl_cmd ${service} ix-ldap status
	then
		ldap_set 0
		cifs_reset
		return 1
	fi

	if cifs_enabled && LDAP_has_samba_schema 
	then
		cifs_restart
	fi

	ldapctl_cmd ${service} ix-pam quietstart
	ldapctl_cmd "${service} ix-cache quietstart &"
	touch "${status_file}"

	return 0
}

ldapctl_stop()
{
	LDAP_init

	if ! ldap_enabled
	then
		ldap_set 1
	fi

	if sssd_running
	then
		sssd_stop
		ldapctl_cmd ${service} ix-sssd start
	fi

	ldapctl_cmd ${service} ix-ldap forcestop
	ldapctl_cmd ${service} ix-nsswitch quietstop
	ldapctl_cmd ${service} ix-pam quietstop
	ldapctl_cmd "${service} ix-cache quietstop &"

	ldap_set 0

	if cifs_enabled && LDAP_has_samba_schema
	then
		cifs_restart
	fi

	ldapctl_cmd ${service} ix-kinit quietstop
	rm -f "${status_file}"
	
	return 0
}

ldapctl_status()
{
	ldapctl_cmd ${service} ix-ldap status
}

name="ldapctl"
start_cmd='ldapctl_start'
status_cmd='ldapctl_status'
stop_cmd='ldapctl_stop'
extra_commands='status'

load_rc_config $name
run_rc_command "$1"
